var e = getApp(), t = require("../../../utils/live-video-common.js");

Page(Object.assign({
    data: {
        headerHeight: e.globalData.headerHeight,
        statusBarHeight: e.globalData.statusBarHeight,
        screenHeight: 1e3,
        options: {
            room_id: "",
            building_name: "",
            anchor_id: ""
        },
        userInfo: {},
        userList: [],
        messageList: [],
        pusher: {
            user_id: "",
            nick_name: "",
            avatar_url: ""
        },
        isEnter: !1,
        rtcConfig: {
            sdkAppID: "",
            userID: "",
            userSig: "",
            enableMic: !0,
            template: ""
        },
        myConfig: {
            enableMic: !0
        },
        lockTime: 0,
        showUserList: !1
    },
    visiter: function() {
        this.setData({
            showUserList: !0
        });
    },
    mergeArrayUserHandle: function(e) {
        var t = this.data.userList;
        return e.forEach(function(e, o) {
            var n = t.filter(function(t, o) {
                return t.user_id === e.user_id;
            });
            n.length > 0 ? (n[0].nick_name = e.nick_name, n[0].avatar_url = e.avatar_url) : t.push(e);
        }), t;
    },
    getUsersInfo: function(t) {
        return new Promise(function(o, n) {
            t.length > 0 ? wx.request({
                method: "get",
                url: e.globalData.uchaozuBase + "/api/miniapps/login/userinfo",
                data: Object.assign({
                    ids: t.join(",")
                }, e.getSecret()),
                success: function(e) {
                    if ("200" == e.data.code) {
                        var t = e.data.data;
                        o(t.map(function(e, t) {
                            return e.role = 3, e;
                        }));
                    } else o([]);
                },
                fail: function(e) {
                    console.log(e), o([]);
                }
            }) : o([]);
        });
    },
    getSdkObj: function(t) {
        var o = e.getMobSecret("/api/wechat/get-trtc-sign", {
            uid: t.user_id
        });
        return console.log(o), new Promise(function(t, n) {
            wx.request({
                url: e.globalData.liveBase + "/api/wechat/get-trtc-sign",
                data: o,
                header: {
                    "content-type": "application/json"
                },
                success: function(o) {
                    if ("0" == o.data.errorno) {
                        var n = {
                            sdkAppID: o.data.data.sdkAppId,
                            userSig: o.data.data.userSign
                        };
                        e.globalData.videoObj = n, t();
                    }
                },
                fail: function(e) {
                    n(e);
                }
            });
        });
    },
    enterRoomSuccess: function() {
        var t = e.getMobSecret("/api/wechat/enter-room", {
            uid: e.globalData.userInfo.user_id,
            room_id: this.data.options.room_id,
            user_type: 1
        });
        wx.request({
            url: e.globalData.liveBase + "/api/wechat/enter-room",
            data: t,
            header: {
                "content-type": "application/json"
            },
            success: function(e) {
                "0" == e.data.errorno ? console.log("进入房间成功，告诉后台") : console.log(e.data.errormsg);
            },
            fail: function(e) {}
        });
    },
    checkVersion: function() {
        var t = e.globalData.SDKVersion + "";
        if (console.log("微信基础库版本号：" + t), !(e.compareVersion(t, "2.10.0") >= 0)) return wx.showModal({
            title: "提示",
            content: "当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。"
        }), !1;
        var o = e.globalData.system;
        if (o.indexOf("iOS") > -1) {
            var n = o.split(" ")[1];
            if (e.compareVersion(n, "7.0.9") < 0) return wx.showModal({
                title: "提示",
                content: "当前系统版本过低，无法使用该功能，请升级到7.0.9及以上版本后重试。"
            }), !1;
        } else if (o.indexOf("Android") > -1) {
            var a = o.split(" ")[1];
            if (e.compareVersion(a, "7.0.8") < 0) return wx.showModal({
                title: "提示",
                content: "当前系统版本过低，无法使用该功能，请升级到7.0.8及以上版本后重试。"
            }), !1;
        }
        return !0;
    },
    getPuserSync: function() {
        try {
            var e = wx.getStorageSync("curr_pusher");
            return e.length ? JSON.parse(e) : null;
        } catch (e) {
            return null;
        }
    },
    onLoad: function(t) {
        var o = this;
        if (t.room_id = Number(t.roomID), t.is_room) {
            var n = o.getPuserSync();
            n && (o.data.pusher = n, o.setData({
                pusher: n
            }));
        }
        t.anchor_id = "", this.setData({
            options: t,
            screenHeight: e.globalData.screenHeight,
            headerHeight: e.globalData.headerHeight,
            statusBarHeight: e.globalData.statusBarHeight
        });
    },
    enterRoomHandle: function(e) {
        var t = this, o = e.sdkAppID, n = e.userSig, a = {
            rtcConfig: {
                sdkAppID: o,
                userID: this.data.rtcConfig.userID + "",
                userSig: n,
                enableMic: this.data.rtcConfig.enableMic,
                template: "custom",
                roomID: Number(this.data.options.room_id),
                cloudenv: "PRO",
                scene: "rtc",
                localVideo: !1,
                localAudio: !0,
                enableEarMonitor: !1,
                enableAutoFocus: !0,
                localMirror: "auto",
                enableAgc: !0,
                enableAns: !0,
                encsmall: !1,
                frontCamera: "front",
                resolution: "HD",
                debugMode: !1,
                beautyLevel: 9,
                audioVolumeType: "media",
                enableIM: !0,
                videoWidth: 540,
                videoHeight: 960,
                minBitrate: 600,
                maxBitrate: 1500,
                enableBackgroundMute: !0
            }
        };
        "" === this.data.pusher.user_id && (a.pusher = this.data.userInfo), this.setData(a, function() {
            t.trtcComponent.enterRoom({
                roomID: t.data.options.room_id
            }).then(function(e) {
                console.log("进房成功！！"), console.log(e), t.data.pusher.user_id === t.data.userInfo.user_id ? t.trtcComponent.publishLocalVideo() : t.trtcComponent.setViewVisible({
                    userID: t.data.userInfo.user_id,
                    streamType: "main",
                    isVisible: !1
                }), t.trtcComponent.publishLocalAudio(), t.trtcComponent.setViewRect({
                    userID: t.data.pusher.user_id,
                    streamType: "main",
                    xAxis: "0rpx",
                    yAxis: "0rpx",
                    width: "750rpx",
                    height: t.data.screenHeight + "rpx"
                });
            }).catch(function(e) {
                console.error("* room joinRoom 进房失败:", e);
            });
        });
    },
    bindTRTCRoomEvent: function() {
        var e = this, t = this.trtcComponent.EVENT;
        this.timestamp = [], this.trtcComponent.on(t.LOCAL_JOIN, function(t) {
            console.log("* room LOCAL_JOIN", t), e.enterRoomSuccess();
        }), this.trtcComponent.on(t.LOCAL_LEAVE, function(e) {
            console.log("* room LOCAL_LEAVE", e);
        }), this.trtcComponent.on(t.ERROR, function(e) {
            console.log("* room ERROR", e);
        }), this.trtcComponent.on(t.REMOTE_USER_JOIN, function(t) {
            console.log("* 远端用户进房", t, e.trtcComponent.getRemoteUserList());
            var o = t.data.userID;
            e.addOnePerson(o);
        }), this.trtcComponent.on(t.REMOTE_USER_LEAVE, function(t) {
            console.log("* 远端用户退出", t, e.trtcComponent.getRemoteUserList());
            var o = e.data.messageList, n = e.data.userList, a = n.filter(function(e, o) {
                return e.user_id !== t.data.userID;
            }), i = n.filter(function(e, o) {
                return e.user_id === t.data.userID;
            });
            0 === i.length && (i[0] = {
                nick_name: t.data.userID
            }), o.push(Object.assign({
                messageText: i[0].nick_name + "离开了直播间"
            }, i[0])), e.setData({
                userList: a,
                messageList: o
            }), setTimeout(function() {
                e.remoteVideoLeave(t.data.userID);
            }, 1e3);
        }), this.trtcComponent.on(t.REMOTE_VIDEO_ADD, function(t) {
            console.log("###远端用户推送视频###", t.data.userID, e.trtcComponent.getRemoteUserList());
        }), this.trtcComponent.on(t.REMOTE_VIDEO_REMOVE, function(t) {
            console.log("* room REMOTE_VIDEO_REMOVE", t, e.trtcComponent.getRemoteUserList());
            var o = t.data;
            e.remoteVideoRemoveRoleUpdate(o.userID);
        }), this.trtcComponent.on(t.REMOTE_AUDIO_ADD, function(t) {
            console.log("* room REMOTE_AUDIO_ADD", t, e.trtcComponent.getRemoteUserList());
            var o = t.data;
            e.trtcComponent.subscribeRemoteAudio({
                userID: o.userID
            });
        }), this.trtcComponent.on(t.REMOTE_AUDIO_REMOVE, function(t) {
            console.log("* room REMOTE_AUDIO_REMOVE", t, e.trtcComponent.getRemoteUserList());
        }), this.trtcComponent.on(t.IM_SDK_READY, function(e) {
            console.log("* room IM_SDK_READY", e);
        }), this.trtcComponent.on(t.IM_MESSAGE_RECEIVED, function(t) {
            console.log("* room IM_MESSAGE_RECEIVED", t);
            var o = t.data.data[0];
            if ("GROUP" === o.conversationType) {
                var n = JSON.parse(o.payload.text);
                return "20000" === n.code && e.backPerson(n.user_id), "20001" === n.code && e.leavePerson(n.user_id), 
                "20010" === n.code && (e.trtcComponent.data.pusher.enableCamera ? e.exitAndEndHandle(o.from) : (e.viewSwitch(e.data.pusher.user_id, o.from), 
                e.roleUpdateFun(o.from), e.setData({
                    pusher: e.getRemoteUserInfo(o.from)
                }))), !1;
            }
            if ("code:10001" === o.payload.data && (e.trtcComponent.data.pusher.enableCamera ? e.exitAndEndHandle(o.from) : (e.viewSwitch(e.data.pusher.user_id, o.from), 
            e.roleUpdateFun(o.from), e.setData({
                pusher: e.getRemoteUserInfo(o.from)
            }))), "code:10002" === o.payload.data) {
                var a = e.getRemoteUserInfo(o.from);
                wx.showToast({
                    icon: "none",
                    title: a.nick_name + "拒绝了您的设为主持人请求。",
                    duration: 3e3
                });
            }
            "code:10003" === o.payload.data && e.remoteVideoLeave(o.from);
        });
    },
    exitAndEndHandle: function(e) {
        var t = this;
        this.trtcComponent.unpublishLocalVideo().then(function() {
            t.trtcComponent.unpublishLocalAudio(), t.trtcComponent.data.exitIMThrottle = !0, 
            t.trtcComponent.exitRoom().then(function() {
                t.setData({
                    rtcConfig: t.data.rtcConfig
                }, function() {
                    t.trtcComponent.enterRoom({
                        roomID: t.data.options.room_id
                    }).then(function(o) {
                        console.log("重新进房成功！"), t.trtcComponent.data.exitIMThrottle = !1, t.data.myConfig.enableMic ? t.trtcComponent.publishLocalAudio() : t.trtcComponent.unpublishLocalAudio(), 
                        t.viewSwitch(t.data.pusher.user_id, e), t.roleUpdateFun(e), t.setData({
                            pusher: t.getRemoteUserInfo(e)
                        });
                    });
                });
            });
        });
    },
    addOnePerson: function(e) {
        var t = this;
        0 === this.data.userList.filter(function(t, o) {
            return t.user_id === e;
        }).length && this.getUsersInfo([ e ]).then(function(e) {
            if (e.length) {
                e.forEach(function(e, o) {
                    e.role = e.user_id === t.data.pusher.user_id ? 2 : 3;
                });
                t.data.userList;
                var o = t.data.messageList;
                o.push(Object.assign({
                    messageText: e[0].nick_name + "进入了直播间"
                }, e[0])), t.setData({
                    userList: t.mergeArrayUserHandle(e),
                    messageList: o
                }), "" === t.data.pusher.avatar_url && t.setData({
                    pusher: t.getRemoteUserInfo(t.data.pusher.user_id)
                });
            }
        });
    },
    getRemoteUserInfo: function(e) {
        var t = this.data.userList.filter(function(t, o) {
            return t.user_id === e;
        });
        return t.length ? t[0] : {
            user_id: e,
            nick_name: e,
            avatar_url: ""
        };
    },
    remoteVideoLeave: function(e) {
        var t = this;
        t.data.pusher.user_id === e && wx.showModal({
            title: t.data.pusher.nick_name + "已经退出了直播。",
            content: "是否改由您来继续直播？",
            cancelText: "保持不变",
            confirmText: "我来直播",
            success: function(o) {
                o.confirm && (t.trtcComponent.publishLocalVideo().then(function() {
                    t.trtcComponent.sendGroupTextMessage({
                        roomID: t.data.options.room_id,
                        message: JSON.stringify({
                            user_id: t.data.userInfo.user_id,
                            code: "20010"
                        })
                    });
                }), t.viewSwitch(e, t.data.userInfo.user_id), t.setData({
                    pusher: {
                        user_id: t.data.userInfo.user_id,
                        nick_name: t.data.userInfo.nick_name,
                        avatar_url: t.data.userInfo.avatar_url
                    }
                }), t.roleUpdateFun(t.data.userInfo.user_id));
            }
        });
    },
    pusherClear: function() {
        this.setData({
            pusher: {
                user_id: "",
                nick_name: "",
                avatar_url: ""
            }
        });
    },
    remoteVideoRemoveRoleUpdate: function(e) {
        var t = this.data.userInfo.user_id, o = this.data.userList, n = e === t;
        o = o.map(function(t, o) {
            return t.user_id === e && (t.role = n ? 1 : 3), t;
        }), this.setData({
            userList: o
        });
    },
    roleUpdateFun: function(e) {
        var t = this.data.userInfo.user_id, o = this.data.userList, n = e === t;
        o = o.map(function(o, a) {
            return o.user_id === e ? o.role = n ? 0 : 2 : o.role = o.user_id === t ? 1 : 3, 
            o;
        }), this.setData({
            userList: o
        });
    },
    userLeaveFun: function(e) {
        var t = this.data.userList;
        t = t.map(function(t, o) {
            return t.user_id === e && (t.role = 4), t;
        }), this.setData({
            userList: t
        });
    },
    userBackFun: function(e) {
        var t = this, o = this.data.userList;
        o = o.map(function(o, n) {
            return o.user_id === e && (e === t.data.userInfo.user_id ? o.role = t.data.pusher.user_id === t.data.userInfo.user_id ? 0 : 1 : o.role = t.data.pusher.user_id === e ? 2 : 3), 
            o;
        }), this.setData({
            userList: o
        });
    },
    viewSwitch: function(e, t) {
        var o = this;
        this.trtcComponent.setViewVisible({
            userID: e,
            isVisible: !1,
            streamType: "main"
        }), setTimeout(function() {
            t !== o.data.userInfo.user_id && o.trtcComponent.subscribeRemoteVideo({
                userID: t,
                streamType: "main"
            }), o.trtcComponent.setViewVisible({
                userID: t,
                isVisible: !0,
                streamType: "main"
            }), o.trtcComponent.setViewRect({
                userID: t,
                streamType: "main",
                xAxis: "0rpx",
                yAxis: "0rpx",
                width: "750rpx",
                height: o.data.screenHeight + "rpx"
            });
        }, 2e3);
    },
    handlePublishAudio: function() {
        if (this.data.myConfig.enableMic) {
            this.trtcComponent.unpublishLocalAudio();
            var e = this.data.myConfig;
            e.enableMic = !1, this.setData({
                myConfig: e
            }, function() {
                wx.showToast({
                    title: "您已关闭麦克风",
                    icon: "none",
                    duration: 500
                });
            });
        } else {
            this.trtcComponent.publishLocalAudio();
            var t = this.data.myConfig;
            t.enableMic = !0, this.setData({
                myConfig: t
            }, function() {
                wx.showToast({
                    title: "您已开启麦克风",
                    icon: "none",
                    duration: 500
                });
            });
        }
    },
    switchCamera: function() {
        this.trtcComponent.switchCamera();
    },
    exitRoom: function() {
        var e = this;
        wx.showModal({
            title: "确认结束直播么？",
            content: "结束直播其他成员也将退出",
            success: function(t) {
                t.confirm ? e.exitRoomHandle() : t.cancel;
            }
        });
    },
    exitRoomHandle: function() {
        var e = this;
        if (null === e.trtcComponent) return !1;
        wx.showLoading({
            title: "登出操作中……"
        }), e.trtcComponent.sendGroupTextMessage({
            roomID: e.data.options.room_id,
            message: JSON.stringify({
                user_id: e.data.userInfo.user_id,
                code: "40000"
            })
        }).then(function() {
            e.trtcComponent.unpublishLocalVideo(), e.trtcComponent.unpublishLocalAudio(), e.trtcComponent.exitRoom().then(function() {
                console.log("退出成功！");
            }), e.closeRoomHandle();
        }, function() {
            wx.showToast({
                title: "通知组内成员失败，强制退出。",
                icon: "none",
                duration: 500
            }), e.trtcComponent.unpublishLocalVideo(), e.trtcComponent.unpublishLocalAudio(), 
            e.trtcComponent.exitRoom().then(function() {
                console.log("退出成功！");
            }), e.closeRoomHandle();
        });
    },
    closeRoomHandle: function() {
        var t = this, o = e.getMobSecret("/api/wechat/close-room", {
            uid: e.globalData.userInfo.user_id,
            room_id: t.data.options.room_id
        });
        wx.request({
            url: e.globalData.liveBase + "/api/wechat/close-room",
            data: o,
            header: {
                "content-type": "application/json"
            },
            success: function(e) {
                "0" == e.data.errorno || wx.showToast({
                    title: e.data.errormsg,
                    icon: "none",
                    duration: 3e3
                }), wx.hideLoading(), wx.reLaunch({
                    url: "/pages/live-video/video-detail/index?roomID=" + t.data.options.room_id
                });
            },
            fail: function(e) {
                reject(e), wx.hideLoading();
            }
        });
    },
    closePerson: function() {
        this.setData({
            showUserList: !1
        });
    },
    countDown: function() {
        var e = this;
        this.setData({
            lockTime: 30
        });
        var t = setInterval(function() {
            var o = e.data.lockTime;
            0 === o ? clearInterval(t) : e.setData({
                lockTime: o - 1
            });
        }, 1e3);
    },
    setHost: function(e) {
        var t = this;
        if (0 !== this.data.lockTime) return !1;
        this.setData({
            showUserList: !1
        });
        var o = e.currentTarget.dataset.uid;
        if (this.data.pusher.user_id !== this.data.userInfo.user_id) o === this.data.userInfo.user_id ? wx.showModal({
            title: this.data.pusher.nick_name + "正在直播",
            content: "是否切换主持人为自己？",
            cancelText: "取消切换",
            confirmText: "确定切换",
            success: function(e) {
                e.confirm && (t.countDown(), t.trtcComponent.publishLocalVideo().then(function() {
                    t.trtcComponent.sendGroupTextMessage({
                        roomID: t.data.options.room_id,
                        message: JSON.stringify({
                            user_id: t.data.userInfo.user_id,
                            code: "20010"
                        })
                    });
                }), t.viewSwitch(t.data.pusher.user_id, t.data.userInfo.user_id), t.setData({
                    pusher: t.getRemoteUserInfo(t.data.userInfo.user_id)
                }), t.roleUpdateFun(t.data.userInfo.user_id));
            }
        }) : (this.countDown(), this.trtcComponent.sendC2CCustomMessage({
            userID: o,
            payload: {
                data: "code:10010",
                description: "邀请您来进行直播，是否接受？",
                extension: ""
            }
        })); else {
            if (o === this.data.userInfo.user_id) return !1;
            this.countDown(), this.trtcComponent.sendC2CCustomMessage({
                userID: o,
                payload: {
                    data: "code:10000",
                    description: "邀请您来进行直播，是否接受？",
                    extension: ""
                }
            });
        }
    },
    onReady: function() {},
    getRoomInfo: function() {
        var t = e.getMobSecret("/api/wechat/get-room-info", {
            uid: e.globalData.userInfo.user_id,
            room_id: this.data.options.room_id
        });
        return console.log(t), new Promise(function(o, n) {
            wx.request({
                url: e.globalData.liveBase + "/api/wechat/get-room-info",
                data: t,
                header: {
                    "content-type": "application/json"
                },
                success: function(e) {
                    o(e);
                },
                fail: function(e) {
                    n(e);
                }
            });
        });
    },
    checkFun: function() {
        var t = this;
        this.getRoomInfo().then(function(o) {
            console.log(o), t.setData({
                isEnter: !0
            }), "0" == o.data.errorno ? 3 == o.data.data.room_status || 4 == o.data.data.room_status ? wx.reLaunch({
                url: "/pages/live-video/video-detail/index?roomID=" + t.data.options.room_id
            }) : (t.trtcComponent = t.selectComponent("#trtc-component"), t.bindTRTCRoomEvent(), 
            t.enterRoomHandle(e.globalData.videoObj)) : (console.log(o.data.errormsg), wx.showLoading({
                title: o.data.errormsg,
                duration: 3e3
            }));
        });
    },
    enterPreHandle: function() {
        var t = this, o = this;
        e.cameraPower().then(function(n) {
            n && e.soundPower().then(function(n) {
                if (n) {
                    var a = e.globalData.userInfo;
                    if (a && a.user_id) {
                        if (!t.checkVersion()) return !1;
                        a.user_id = a.user_id + "", console.log("###当前pusher为：####" + JSON.stringify(t.data.pusher));
                        var i = !("" !== t.data.pusher.user_id && t.data.pusher.user_id !== t.data.userInfo.user_id), r = o.data.rtcConfig;
                        r.userID = a.user_id;
                        var s = [ {
                            user_id: a.user_id,
                            nick_name: a.nick_name,
                            avatar_url: a.avatar_url,
                            role: i ? 0 : 1
                        } ];
                        t.setData({
                            userInfo: a,
                            userList: s,
                            rtcConfig: r
                        }), console.log("登录的人是" + a.user_id), a.videoObj && a.videoObj.sdkAppId ? o.checkFun() : o.getSdkObj(a).then(function() {
                            o.checkFun();
                        });
                    } else wx.navigateTo({
                        url: "/pages/getinfo/index"
                    }), e.globalData.needBack = !0;
                }
            });
        });
    },
    onShow: function() {
        if (wx.setKeepScreenOn({
            keepScreenOn: !0
        }), this.data.isEnter) return console.log("onshow 执行"), this.trtcComponent.sendGroupTextMessage({
            roomID: this.data.options.room_id,
            message: JSON.stringify({
                user_id: this.data.userInfo.user_id,
                code: "20000"
            })
        }), !1;
        this.enterPreHandle();
    },
    onHide: function() {
        if (console.log("####页面隐藏!"), !this.data.isEnter) return !1;
        this.trtcComponent.sendGroupTextMessage({
            roomID: this.data.options.room_id,
            message: JSON.stringify({
                user_id: this.data.userInfo.user_id,
                code: "20001"
            })
        }), this.data.pusher.user_id !== this.data.userInfo.user_id ? wx.setStorage({
            key: "curr_pusher",
            data: JSON.stringify(this.data.pusher)
        }) : wx.removeStorage({
            key: "curr_pusher"
        }), wx.setKeepScreenOn({
            keepScreenOn: !1
        });
    },
    onUnload: function() {
        console.log("####页面卸载!");
    },
    onPullDownRefresh: function() {},
    onReachBottom: function() {},
    onShareAppMessage: function(t) {
        var o = this, n = "/images/video/project_temp.jpg";
        if (null != e.globalData.userInfo) {
            var a = e.getMobSecret("/api/wechat/get-share-image", {
                uid: e.globalData.userInfo.user_id,
                text: this.data.options.building_name
            }, "GET", 604800);
            console.log(a), n = e.globalData.liveBase + "/api/wechat/get-share-image?sign=" + a.sign + "&secret_id=" + a.secret_id + "&uid=" + e.globalData.userInfo.user_id + "&text=" + o.data.options.building_name + "&timestamp=" + a.timestamp + "&valid_time=604800";
        }
        return {
            title: o.data.options.building_name + "-看房直播",
            imageUrl: n,
            path: "/pages/live-video/live-video/room?room_id=" + o.data.options.room_id + "&building_name=" + o.data.options.building_name + "&anchor_id=" + o.data.userInfo.user_id
        };
    }
}, t));